#!/usr/bin/env node

const http = require('http'),
      url  = require('url'),
      qs   = require('querystring');

let items  = [];

function genPage(){

  let  html = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>TodoLIst</title>
    </head>
    <body>
      <h1>TodoList</h1>
      <form action="http://192.168.73.144:8080" method="GET">
        <input type="text" name ='item'>
        <input type='submit' value='submit'>
      </form>
      <ul id='items'>
        ${items.map(i=>'<li>' + i + '</li>').join('\n')}
      </ul>
    </body>
    </html>`;
  return html;
}


http.createServer((req,res)=>{
  //let dom = (items.length===0)?'' : items.map(i=>'<li>'+i+'</li>').join('\n');
  let addr = url.parse(req.url); 
  if(addr.pathname !== '/'){
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found</h1>');
    return;
  }
  let item = qs.parse(addr.query).item;
  if(item !== '' && typeof item !=='undefined') items.push(item);

  res.writeHead(200,{
    'Content-Type':'text/html',
    'Content-Length':Buffer.byteLength(genPage())
    
  });

  res.end(genPage());

}).listen(8080);

